from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required


from wjContact.computers.models import Computer
from wjContact.computers.views.forms import ComputerForm


def computer_add(request, main_object_id=None):
    return computer(request, main_object_id=main_object_id)

def computer_edit(request, main_object_id=None):
    return computer(request, main_object_id=main_object_id)


def computer(request, main_object_id=None):
    """ """
    ## See contrib/admin/views.main.add_stage() for some ideas...   
    ## If user has hit the submit button, the request method will be 'POST'...
    if request.method == 'POST':
        ## The following works whether we are an adding form or an editing
        ## form.
        for key in request.POST.keys():
            ## The key should be 'add_another_pet', 'add_another_phone', etc
            if key.startswith('add_another'):
                base_name = key.split('_')[2]
                plural_name = base_name + 's'
                request_data = dict(request.POST)
                new_request_data = {}
                for key in request_data:
                    new_request_data[key] = request_data[key][0]   
                if main_object_id:
                    ## we are editing.      
                    object = Computer.objects.get(pk=main_object_id)                 
                    filled_form = ComputerForm(initial=new_request_data, main_object=object)
                else:
                    ## we are adding.
                    filled_form = ComputerForm(initial=new_request_data)
                    
                filled_form.__getattribute__(plural_name).add_fields(1)
                filled_form.put_fieldlists_into_form_fields()
                #pdb.set_trace()        
                ff=filled_form
                #pdb.set_trace()
                msg = "Here are the additional entry fields you asked for..."
                request.user.message_set.create(message=msg)
                return render_to_response(
                  'computer.html', 
                  {'form' : filled_form},
                  context_instance=RequestContext(request)
                  )          
        if main_object_id:
            ## We are an editing form    
            object = Computer.objects.get(pk=main_object_id)  
            filled_form =  ComputerForm(request.POST, main_object=object)
        else:
             ## We are an adding form       
            filled_form = ComputerForm(request.POST)
        ## handle_contact_form does validation and re-rendering or directing on. 
        ff=filled_form
        #pdb.set_trace() 
        ##process_form(request, filled_form, template, redirect_to):  
        template = "computer.html"
        redirect_to = "http://localhost:8000/computers"
        return handle_computer_form(request, filled_form)                
        #return handle_contact_form(request, filled_form)   
    ## If request.method is not 'POST', then the user has not yet hit the 
    ## submit button  -->  render an empty form for them to fill in ...       
    else:  
        if main_object_id:   
            #pdb.set_trace() 
            object = Computer.objects.get(pk=main_object_id)
            empty_form = ComputerForm(main_object=object)
#            emf=empty_form 
#            pdb.set_trace() 
            form_instructions = "Edit an existing Computer here!"
        else:
            empty_form = ComputerForm()
            form_instructions = "Add new Computer here!"
    ef=empty_form
    #pdb.set_trace()      
    return render_to_response(
        'computer.html', 
        {
         'form' : empty_form,
         'form_instructions': form_instructions,
         },
        context_instance=RequestContext(request)
        )                                     
#computer = login_required(computer) 

def handle_computer_form(request, filled_form): 
    """
    Check that the filled form is valid, and check for duplicates. 
    
     1. If everything checks out ok: get the form to save() itself and return
        the 'save and redirect' method.
     2. If there are duplicates, instead render a page listing these.
     3. If the form data is invalid in some way, re-render the form with the
        error messages displayed, so that the user can fix them.
     """
    ff = filled_form
    #pdb.set_trace()
    if not (filled_form.is_valid()):
        #pdb.set_trace()
        ## If it's not valid, render failure message
        msg = "Couldn't add new computer using the details given. Please fix the problems listed below and I'll try again :)"
        request.user.message_set.create(message=msg)
        return render_to_response('computer.html',
             {'form': filled_form}, 
             context_instance=RequestContext(request) )  
    ## Check that this entry does not duplicate an existing one...
    ## The check_for_duplicates() method returns either an appropriate
    ## response object, which is 'True', and we pass it on, or else it 
    ## returns None. Should consider refactoring
    ## this, to keep views type stuff out of the file.
    ## Only check for duplicates if we are adding a new entry, not if we are
    ## updating an existing one.
    redirect_to = "http://localhost:8000/computers"
    saver = save_and_redirect(request, filled_form, redirect_to=redirect_to, msg='New Computer succesfully added')
    ## And if there are no duplicates, save the data from this form 
    ## to the database, and redirect to the list of all existing 
    ## contacts. Always return an HttpResponseRedirect after 
    ## successfully dealing with POST data. This prevents data from 
    ## being posted twice if a user hits the Back button. 
    return saver
 

def computer_list(request):
    """ List all Computers."""
    computers = Computer.objects.all().order_by('cbv_no')
    return render_to_response(
        'computer_list.html', 
        {'computer_list': computers},
        context_instance=RequestContext(request))   
    
def save_and_redirect(request, form, redirect_to=None, msg='Saved'):
    form.save()
    msg = " %s" % msg
    request.user.message_set.create(message=msg)
    return HttpResponseRedirect(redirect_to) 
    
"""

Add another button to the Recipient form saying 'Save and continue to sales'.
Re-label existing button to 'Just Save' or something. 

Sales page - shows some identifying details of the user (name etc) at the top,
then some spaces to add sales items. Computers can either be added by cbv_no 
(if known) *or* you can get redirected to a form allowing you to add a new
computer(this will actualy be a rudimentary version of the form used by the 
build-room as well)
   --> needs additions to views, templates, urls.py,and global_nav 

Also on Sales page, can add one or more seperate items (extra stuff from the shop)
Use a repeating fieldlist, with minimum 'item name' and item description.

models.Computer.get_sold_status() --> Will let us add a column to the 
computerlist page showing whether a computer has been sold yet.

 
"""